#include "SpeedProfileWidget.h"

SpeedProfileWidget::SpeedProfileWidget(QWidget *parent) : QWidget(parent)
{
    dataPoints.clear();
    updateTimer = new QTimer;
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(update()));
    updateTimer->start(50);
    vAxisMin = 0;
    vAxisMax = 100;
    hAxisMin = 0;
    hAxisMax = 100;
}

void SpeedProfileWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    drawAxises(&painter);
    drawProfile(&painter);
    QWidget::paintEvent(event);
}

void SpeedProfileWidget::reset()
{
    dataPoints.clear();
}

void SpeedProfileWidget::setAxisNames(QString verticalName, QString horizontalName)
{
    vAxisName = verticalName;
    hAxisName = horizontalName;
}

void SpeedProfileWidget::setAxisRanges(qreal vMin, qreal vMax, qreal hMin, qreal hMax)
{
    // vertical
    vAxisMin = vMin;
    if (vAxisMin < 0) vAxisMin *= 1.1;
    else vAxisMin *= 0.9;
    vAxisMax = vMax;
    if (vAxisMax > 0) vAxisMax *= 1.1;
    else vAxisMax *= 0.9;
    // horizontal
    hAxisMin = hMin;
    if (hAxisMin < 0) hAxisMin *= 1.1;
    else hAxisMin *= 0.9;
    hAxisMax = hMax;
    if (hAxisMax > 0) hAxisMax *= 1.1;
    else hAxisMax *= 0.9;
}

void SpeedProfileWidget::addPoint(QPointF *dataPoint)
{
    dataPoints.append(dataPoint);
}

void SpeedProfileWidget::mouseMoveEvent(QMouseEvent *event)
{
    QWidget::mouseMoveEvent(event);
}

void SpeedProfileWidget::pretendMouseOver(qreal horizontalValue)
{
    Q_UNUSED(horizontalValue)
    return;
}

void SpeedProfileWidget::drawAxises(QPainter *p)
{
    p->save();
    QPen pen;
    pen.setWidth(2);
    pen.setColor(Qt::black);
    p->setPen(pen);
    // horizontal axis
    double originY = vAxisMin / (vAxisMax - vAxisMin)
                    * (height() - 20) - 10 + height();
    p->drawLine(10, originY, width() - 10, originY);
    p->drawLine(width() - 10, originY, width() - 15, originY + 5);
    p->drawLine(width() - 10, originY, width() - 15, originY - 5);
    p->drawText(width() - 20, originY - 10, hAxisName);
    // vertical axis
    double originX = - hAxisMin / (hAxisMax - hAxisMin)
                    * (width() - 20) + 10;
    p->drawLine(originX, height() - 10, 10, 10);
    p->drawLine(originX, 10, 5, 15);
    p->drawLine(originX, 10, 15, 15);
    p->drawText(originX + 10, 20, vAxisName);
    p->restore();
}

void SpeedProfileWidget::drawProfile(QPainter *p)
{
    p->save();
    QPen pen;
    pen.setWidth(2);
    pen.setColor(Qt::blue);
    p->setPen(pen);
    for (int i = 0; i < dataPoints.size(); ++i)
    {
        QPointF point;
        point.rx() = (dataPoints.at(i)->x() - hAxisMin) / (hAxisMax - hAxisMin)
                * (width() - 20) + 10;
        point.ry() = -(dataPoints.at(i)->y() - vAxisMin) / (vAxisMax - vAxisMin)
                * (height() - 20) - 10 + height();
        p->drawPoint(point);
    }
    p->restore();
}
